import React, { Component } from 'react'
import {
  View,
  StyleSheet,
  Image,
  Text,
  ScrollView,
  ImageBackground,
  TouchableOpacity
} from 'react-native'

import RNFS from 'react-native-fs'
import ImagePicker from 'react-native-image-crop-picker'
import NavBar from '../../../../../components/PublicHeader';
import fetchWebApi from '../../../../../public/WebApi/fetchBase';
import getStorageValue from '../../../../../utils/getStorageValue';
import Layer from '../../../../../utils/Layer';
import {
  Constant
} from '../../../../../public/js/constant';
import {
  POST_APPCARD_ADD,
  POST_ALBUMINFDOATA_UPLOAD
} from '../../../../../public/WebApi/myInfoDataInterface/userInfoListApi';

export default class addCertificate extends Component {
  constructor(props) {
    super(props)
    const {
      cardType
    } = this.props.navigation.state.params
    this.state = {
      topTitle: "添加驾驶证",
      certificateBg: require("../../../../../assets/images/iconResources/frontofDriverLicense.png"),
      buttonIconAdd: require("../../../../../assets/images/iconResources/certificateAddition.png"),
      certificateBg2: require("../../../../../assets/images/iconResources/backofDriverLicense.png"),
      promptLanguage: "上传驾驶证主页",
      promptLanguage2: "上传身份证背面",
      cardType: cardType,
      contents: '',
      typeArr: '',
      len: [],
      positive: '',
      back: ''
    };
  }

  componentDidMount = () => {

  }

  //上传证件照
  async postAppcard() {
    const {
      cardType,
      positive,
      back
    } = this.state
    if (positive != '' &&
      back != '') {
      const res = await fetchWebApi(POST_APPCARD_ADD,
        {
          token: await getStorageValue(Constant.TOKEN),
          cardType: cardType,
          frontPath: positive,
          backPath: back
        }, 'POST')
      if (res.status = 200) {
        Layer.showMsg('添加成功')
        this.props.navigation.state.params.refresh()
        this.props.navigation.goBack()// 返回上一级
      }
    }
  }

  uploadPictures(flag) {
    ImagePicker.openPicker({
      width: 300,
      height: 400,
    }).then(images => {
      // 将路径分割，取出图片类型
      this.state.len.push(images.path.split('.'))
      this.state.len.map(item => {
        this.setState({
          typeArr: item[item.length - 1]
        })
      })
      if (flag) {
        this.setState({
          positive: images.path
        })
      } else {
        this.setState({
          back: images.path
        })
      }
      RNFS.readFile(images.path, 'base64')
        .then(content => {
          // base64 本地相册地址转换
          this.setState({
            contents: content
          })
          this.uploadDatasbase(flag)
        })
    })
      .catch(err => {
        console.log(err);
      })
  }

  async uploadDatasbase(flag) {
    const {
      contents,
      typeArr
    } = this.state
    const res = await fetchWebApi(POST_ALBUMINFDOATA_UPLOAD,
      {
        fileContent: contents,
        type: typeArr
      }, 'POST')
    if (flag) {
      this.setState({
        positive: res.url
      })
    } else {
      this.setState({
        back: res.url
      })
    }
  }

  render() {
    const {
      topTitle,
      positive,
      certificateBg,
      buttonIconAdd,
      promptLanguage,
      back,
      certificateBg2,
      promptLanguage2
    } = this.state
    return (
      <View style={styles.padlrWarper}>
        {/* 导航栏 */}
        <NavBar
          navigation={this.props.navigation}
          title={topTitle}
          titleColor={"#333"}
          right={'确定'}
          pressRight={() => {
            this.postAppcard()
          }}
        />
        <ScrollView>
          <View style={styles.padlr}>
            {/* 证件提示文本 */}
            <Text style={styles.titleCertificatesText}>请上传驾驶证</Text>
            <Text style={styles.certificatesText}>确保证件清晰完整</Text>
            {/* 添加驾驶证件 */}
            <View style={styles.item}>
              <TouchableOpacity onPress={() => {
                this.uploadPictures(true)
              }}>
                <ImageBackground style={styles.itemBg}
                  source={positive == '' ?
                    certificateBg :
                    { uri: positive }}>
                  <View style={styles.photoDisplayoDetails} >
                    <Image
                      style={styles.buttonIconAdd}
                      source={positive == '' ?
                        buttonIconAdd : null}
                    />
                    <Text style={styles.promptLanguage}>
                      {positive == '' ?
                        promptLanguage : null}
                    </Text>
                  </View>
                </ImageBackground>
              </TouchableOpacity>
            </View>
            <View style={styles.item}>
              <TouchableOpacity onPress={() => {
                this.uploadPictures(false)
              }}>
                <ImageBackground style={styles.itemBg}
                  source={back == '' ?
                    certificateBg2 :
                    { uri: back }}>
                  <View style={styles.photoDisplayoDetails} >
                    <Image
                      style={styles.buttonIconAdd}
                      source={back == '' ?
                        buttonIconAdd : null}
                    />
                    <Text style={styles.promptLanguage}>
                      {back == '' ?
                        promptLanguage2 : null}
                    </Text>
                  </View>
                </ImageBackground>
              </TouchableOpacity>
            </View>
          </View>
        </ScrollView>
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    height: 32,
    backgroundColor: 'transparent'
  },
  padlrWarper: {
    backgroundColor: "rgb(245,245,245)",
    flex: 1,
  },
  padlr: {
    paddingLeft: 40,
    paddingRight: 40,
    paddingTop: 40,
    flexDirection: "column",
    alignItems: "center"
  },
  titleCertificatesText: {
    color: "#333",
    fontSize: 20,
    fontWeight: "700",
    marginBottom: 10
  },
  certificatesText: {
    color: "#333",
    fontSize: 13
  },
  item: {
    marginTop: 30,
    width: "100%",
    height: 200,
    borderRadius: 20,
    flexDirection: "column",
    justifyContent: "space-around"
  },
  itemBg: {
    width: "100%",
    height: 200,
    borderRadius: 10
  },
  photoDisplayoDetails: {
    height: "100%",
    padding: 30,
    flexDirection: "column",
    justifyContent: "space-evenly",
    alignItems: "center",
  },
  buttonIconAdd: {
    width: 60,
    height: 60
  },
  promptLanguage: {
    color: "#fff",
    fontSize: 16
  },
})